﻿
// DLLInjectorMFCDlg.cpp: 实现文件
//

#include "pch.h"
#include "framework.h"
#include "DLLInjectorMFC.h"
#include "DLLInjectorMFCDlg.h"
#include "afxdialogex.h"
#include <Windows.h>
#include <iostream>
#include <string>
#include <tlhelp32.h>
#include <tchar.h>

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

// 用于应用程序“关于”菜单项的 CAboutDlg 对话框

class CAboutDlg : public CDialogEx
{
public:
	CAboutDlg();

	// 对话框数据
#ifdef AFX_DESIGN_TIME
	enum
	{
		IDD = IDD_ABOUTBOX
	};
#endif

protected:
	virtual void DoDataExchange(CDataExchange * pDX);    // DDX/DDV 支持

// 实现
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX)
{
}

void CAboutDlg::DoDataExchange(CDataExchange * pDX)
{
	CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()


// CDLLInjectorMFCDlg 对话框



CDLLInjectorMFCDlg::CDLLInjectorMFCDlg(CWnd * pParent /*=nullptr*/)
	: CDialogEx(IDD_DLLINJECTORMFC_DIALOG, pParent)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CDLLInjectorMFCDlg::DoDataExchange(CDataExchange * pDX)
{
	CDialogEx::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_EDIT1, winClassName);
	DDX_Control(pDX, IDC_EDIT2, winTitleName);
	DDX_Control(pDX, IDC_EDIT3, dllPath);
	DDX_Control(pDX, IDC_BUTTON1, injectBtn);
	DDX_Control(pDX, IDC_BUTTON2, uninjectBtn);
	DDX_Control(pDX, IDC_BUTTON3, saveConfigBtn);
}

BEGIN_MESSAGE_MAP(CDLLInjectorMFCDlg, CDialogEx)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BUTTON1, &CDLLInjectorMFCDlg::OnBnClickedButton1)
	ON_BN_CLICKED(IDC_BUTTON2, &CDLLInjectorMFCDlg::OnBnClickedButton2)
	ON_BN_CLICKED(IDC_BUTTON3, &CDLLInjectorMFCDlg::OnBnClickedButton3)
END_MESSAGE_MAP()


// CDLLInjectorMFCDlg 消息处理程序

BOOL CDLLInjectorMFCDlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();

	// 将“关于...”菜单项添加到系统菜单中。

	// IDM_ABOUTBOX 必须在系统命令范围内。
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu * pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != nullptr)
	{
		BOOL bNameValid;
		CString strAboutMenu;
		bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
		ASSERT(bNameValid);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// 设置此对话框的图标。  当应用程序主窗口不是对话框时，框架将自动
	//  执行此操作
	SetIcon(m_hIcon, TRUE);			// 设置大图标
	SetIcon(m_hIcon, FALSE);		// 设置小图标

	CString winClassName = "''";
	CString winTitleName = "''";
	CString dllPath = "''";

	GetPrivateProfileString("Config", "winClassName", winClassName, winClassName.GetBuffer(MAX_PATH), MAX_PATH, "./Config.ini");
	GetPrivateProfileString("Config", "winTitleName", winTitleName, winTitleName.GetBuffer(MAX_PATH), MAX_PATH, "./Config.ini");
	GetPrivateProfileString("Config", "dllPath", dllPath, dllPath.GetBuffer(MAX_PATH), MAX_PATH, "./Config.ini");

	// 去掉单引号
	winClassName.Replace("'", "");
	winTitleName.Replace("'", "");
	dllPath.Replace("'", "");

	this->winClassName.SetWindowTextA(winClassName);
	this->winTitleName.SetWindowTextA(winTitleName);
	this->dllPath.SetWindowTextA(dllPath);

	return TRUE;  // 除非将焦点设置到控件，否则返回 TRUE
}

void CDLLInjectorMFCDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialogEx::OnSysCommand(nID, lParam);
	}
}

// 如果向对话框添加最小化按钮，则需要下面的代码
//  来绘制该图标。  对于使用文档/视图模型的 MFC 应用程序，
//  这将由框架自动完成。

void CDLLInjectorMFCDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // 用于绘制的设备上下文

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// 使图标在工作区矩形中居中
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// 绘制图标
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialogEx::OnPaint();
	}
}

BOOL RemoteLoadLibrary(DWORD dwProcessID, char * lpszDll);
BOOL RemoteFreeLibrary(DWORD dwProcessID, char * lpszDll);
BOOL SetPrivilege(LPCTSTR lpszPrivilege, BOOL bEnablePrivilege);

BOOL SetPrivilege(LPCTSTR lpszPrivilege, BOOL bEnablePrivilege)
{
	TOKEN_PRIVILEGES tp;      //用来储存特权值信息的结构体
	HANDLE hToken;				  //Token的句柄
	LUID luid;

	//1.打开一个与进程相关联的访问token
	if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
	{
		printf("OpenProcessToken failed: %u\n", GetLastError());
		return FALSE;
	}

	//2.查找系统权限值并储存到luid中
	if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
	{

		printf("LookupPrivilegeValue error: %u\n", GetLastError());
		return FALSE;
	}

	//3.将这些都存入到TOKEN_PRIVILEGES结构体中
	tp.PrivilegeCount = 1;
	tp.Privileges[0].Luid = luid;
	if (bEnablePrivilege)  //根据判断本函数的第二个参数设置属性
	{
		tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
	}
	else
	{
		tp.Privileges[0].Attributes = 0;
	}

	//4.提权
	if (!AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), (PTOKEN_PRIVILEGES)NULL, (PDWORD)NULL))
	{
		printf("AdjustTokenPrivileges error:%u\n", GetLastError());
		return FALSE;
	}

	if (GetLastError() == ERROR_NOT_ALL_ASSIGNED)
	{
		printf("The token dose not have the specified privilege.\n");
		return FALSE;
	}
	return TRUE;
}

/// <summary>
/// 将DLL注入到指定进程
/// </summary>
/// <param name="dwProcessID">进程ID</param>
/// <param name="lpszDll">DLL路径</param>
/// <returns>TRUE成功，FALSE失败</returns>
BOOL RemoteLoadLibrary(DWORD dwProcessID, char * lpszDll)
{
	// 打开目标进程
	HANDLE hProcess = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_VM_OPERATION | PROCESS_VM_WRITE, FALSE, dwProcessID);
	// 向目标进程地址空间写入DLL名称
	DWORD dwSize;
	SIZE_T dwWritten;

	dwSize = strlen(lpszDll) + 1;
	LPVOID lpBuf = VirtualAllocEx(hProcess, NULL, dwSize, MEM_COMMIT, PAGE_READWRITE);
	if (NULL == lpBuf)
	{
		CloseHandle(hProcess);
		return FALSE;
	}
	if (WriteProcessMemory(hProcess, lpBuf, (LPVOID)lpszDll, dwSize, &dwWritten))
	{
		// 要写入字节数与实际写入字节数不相等，仍属失败
		if (dwWritten != dwSize)
		{
			VirtualFreeEx(hProcess, lpBuf, dwSize, MEM_DECOMMIT);
			CloseHandle(hProcess);
			return FALSE;
		}
	}
	else
	{
		CloseHandle(hProcess);
		return FALSE;
	}
	// 不再加载已载入Dll(只加载一次)
	{
		// 使目标进程调用GetModuleHandle，获得DLL在目标进程中的句柄
		DWORD dwHandle, dwID;
		LPVOID pFunc = GetModuleHandleA;
		HANDLE hThread = CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)pFunc, lpBuf, 0, &dwID);
		// 等待GetModuleHandle运行完毕
		WaitForSingleObject(hThread, INFINITE);
		// 获得GetModuleHandle的返回值
		GetExitCodeThread(hThread, &dwHandle);
		CloseHandle(hThread);
		if (dwHandle != NULL)
		{
			VirtualFreeEx(hProcess, lpBuf, dwSize, MEM_DECOMMIT);
			CloseHandle(hProcess);
			return TRUE;
		}
	}
	// 使目标进程调用LoadLibrary，加载DLL
	DWORD dwID;
	LPVOID pFunc = LoadLibraryA;
	HANDLE hThread = CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)pFunc, lpBuf, 0, &dwID);
	// 等待LoadLibrary加载完毕
	WaitForSingleObject(hThread, INFINITE);
	// 释放目标进程中申请的空间
	VirtualFreeEx(hProcess, lpBuf, dwSize, MEM_DECOMMIT);
	CloseHandle(hThread);
	CloseHandle(hProcess);
	return TRUE;
}

BOOL RemoteFreeLibrary(DWORD dwProcessID, char * lpszDll)
{
	BOOL bMore = FALSE, bFound = FALSE;
	HANDLE hSnapshot, hProcess, hThread;
	HMODULE hModule = NULL;
	MODULEENTRY32 me = { sizeof(me) }; //定义一个用于储存模块快照的结构体
	LPTHREAD_START_ROUTINE pThreadProc;

	//1.
	//dwPID=notepad进程ID
	//使用TH32CS_SNAPMODULE参数
	//获取加载到notepad进程的DLL名称
	hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, dwProcessID);

	//此函数检索与进程相关联的第一个模块的信息
	bMore = Module32First(hSnapshot, &me);

	for (; bMore; bMore = Module32Next(hSnapshot, &me))   //bMore用于判断该进程的模块快照是否还有，bFound用于判断是否找到了我们想要卸载的dll模块
	{
		if (!_tcsicmp((LPCTSTR)me.szModule, lpszDll) || !_tcsicmp((LPCTSTR)me.szExePath, lpszDll))
		{
			bFound = TRUE;
			break;
		}
	}

	if (!bFound)
	{
		CloseHandle(hSnapshot);
		return FALSE;
	}
	//2. 通过进程PID获取进程句柄
	if (!(hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwProcessID)))
	{
		_tprintf("OpenProcess(%d) failed!!![%d]\n", dwProcessID, GetLastError);
		return FALSE;
	}
	//3. 获取FreeLibrary函数的地址
	hModule = GetModuleHandle("kernel32.dll");
	pThreadProc = (LPTHREAD_START_ROUTINE)GetProcAddress(hModule, "FreeLibrary");
	//4.创建线程来执行FreeLibrary(modBaseAddr要卸载的dll模块基址)
	hThread = CreateRemoteThread(hProcess, NULL, 0, pThreadProc, me.modBaseAddr, 0, NULL);
	WaitForSingleObject(hThread, INFINITE);
	CloseHandle(hThread);
	CloseHandle(hProcess);
	CloseHandle(hSnapshot);
	return TRUE;
}

//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR CDLLInjectorMFCDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}

// 注入DLL
void CDLLInjectorMFCDlg::OnBnClickedButton1()
{
	CString dllPath;
	CString winClassName;
	CString winTitleName;
	this->dllPath.GetWindowTextA(dllPath);
	this->winClassName.GetWindowTextA(winClassName);
	this->winTitleName.GetWindowTextA(winTitleName);

	DWORD pId = 0;
	CWnd * cWnd = FindWindowA(winClassName, winTitleName);
	if (cWnd == nullptr)
	{
		SetWindowText("DLL注入器 - 注入DLL失败，未找到目标进程窗口");
		return;
	}
	GetWindowThreadProcessId(cWnd->GetSafeHwnd(), &pId);
	if (pId == 0)
	{
		SetWindowText("DLL注入器 - 注入DLL失败，未找到目标进程");
		return;
	}

	if (RemoteLoadLibrary(pId, (LPSTR)(LPCSTR)dllPath))
	{
		SetWindowText("DLL注入器 - 注入DLL成功");
	}
	else
	{
		SetWindowText("DLL注入器 - 注入DLL失败");
	}
}

// 卸载DLL
void CDLLInjectorMFCDlg::OnBnClickedButton2()
{
	CString dllPath;
	CString winClassName;
	CString winTitleName;
	this->dllPath.GetWindowTextA(dllPath);
	this->winClassName.GetWindowTextA(winClassName);
	this->winTitleName.GetWindowTextA(winTitleName);

	DWORD pId = 0;
	CWnd * cWnd = FindWindowA(winClassName, winTitleName);
	if (cWnd == nullptr)
	{
		SetWindowText("DLL注入器 - 注入DLL失败，未找到目标进程窗口");
		return;
	}
	GetWindowThreadProcessId(cWnd->GetSafeHwnd(), &pId);
	if (pId == 0)
	{
		SetWindowText("DLL注入器 - 注入DLL失败，未找到目标进程");
		return;
	}

	if (SetPrivilege(SE_DEBUG_NAME, TRUE))
	{
		bool uninjectStatus = RemoteFreeLibrary(pId, (LPSTR)(LPCSTR)dllPath);
		if (uninjectStatus)
		{
			SetWindowText("DLL注入器 - DLL卸载成功");
		}
		else
		{
			SetWindowText("DLL注入器 - DLL卸载失败");
		}
	}
	else
	{
		SetWindowText("DLL注入器 - DLL卸载失败，提权失败");
	}
}

// 保存配置
void CDLLInjectorMFCDlg::OnBnClickedButton3()
{
	CString winClassName;
	CString winTitleName;
	CString dllPath;
	this->winClassName.GetWindowTextA(winClassName);
	this->winTitleName.GetWindowTextA(winTitleName);
	this->dllPath.GetWindowTextA(dllPath);

	// 添加单引号
	dllPath.Insert(0, "'");
	dllPath.Append("'");

	winClassName.Insert(0, "'");
	winClassName.Append("'");

	winTitleName.Insert(0, "'");
	winTitleName.Append("'");

	WritePrivateProfileString("Config", "winClassName", winClassName, "./Config.ini");
	WritePrivateProfileString("Config", "winTitleName", winTitleName, "./Config.ini");
	WritePrivateProfileString("Config", "dllPath", dllPath, "./Config.ini");

	SetWindowText("DLL注入器 - 保存配置成功");
}
